package com.itheima.springTask;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 定时任务
 */
@Component
@Slf4j
public class AliOssCleanUpJunkFiles {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定时任务，清理垃圾图片
     * @throws Exception
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void cleanUpJunkFiles() throws Exception {
        log.info("开始清理垃圾图片...");
        //计算redis两个集合的差值，就是所有的垃圾图片
        Set diff = redisTemplate.opsForSet().difference("setmealPicSetAli", "setmealPicSetDb");
        //判断集合是否不为空，即是否有垃圾图片
        if (diff != null && diff.size() > 0) {
            //删除垃圾图片
            for (Object o : diff) {
                String url = o.toString();
                String prefix = "aliyuncs.com/";
                int index = url.lastIndexOf(prefix);
                if (index != -1) {
                    String objectName = url.substring(index + prefix.length());
                    log.info("删除垃圾图片：{}", objectName);
                    aliOssUtil.delete(objectName);
                } else {
                    log.warn("非法URL格式，无法提取objectName: {}", url);
                    continue;
                }
            }
        }
        //清空redis集合setmealPicSetAli和setmealPicSetDb
        redisTemplate.delete("setmealPicSetAli");
        redisTemplate.delete("setmealPicSetDb");
        log.info("清理垃圾图片完成...");
    }
}
